package com.orifine.sql.chain;

import java.util.LinkedHashMap;
import java.util.Map;

import com.orifine.sql.SyntaxString;

public class ChainRestrictions implements ChainRestrictionsElement {
	private Map<ChainRestrictionsElement, ChainRestrictionsType> elements = new LinkedHashMap<ChainRestrictionsElement, ChainRestrictionsType>();
	
	public ChainRestrictions and(ChainRestrictionsElement restriction){
		elements.put(restriction, ChainRestrictionsType.AND);
		return this;
	}
	
	public ChainRestrictions or(ChainRestrictionsElement restriction){
		elements.put(restriction, ChainRestrictionsType.OR);
		return this;
	}

	@Override
	public void chain(SyntaxString out) {
		boolean isFirst = true;
		for(ChainRestrictionsElement element : elements.keySet()){
			ChainRestrictionsType elementType = elements.get(element);
			
			if(isFirst){
				isFirst = false;
			} else {
				switch(elementType){
				case AND:
					out.addWord("AND");
					break;
				case OR:
					out.addWord("OR");
					break;
				}
			}
			
			if(element instanceof ChainRestrictions){
				out.append("(");
				element.chain(out);
				out.append(")");
			} else {
				element.chain(out);
			}
		}
	}

	@Override
	public String sql() {
		SyntaxString syntaxString = new SyntaxString();
		chain(syntaxString);
		return syntaxString.toString();
	}
}
